import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';

/**
 * 等待容器中的所有图片加载完成
 * @param {HTMLElement} container - 容器元素
 * @returns {Promise} 加载完成的Promise
 */
const waitForImages = (container) => {
    const images = container.querySelectorAll('img');
    if (images.length === 0) {
        return Promise.resolve();
    }

    const imagePromises = Array.from(images).map(img => {
        return new Promise((resolve, reject) => {
            if (img.complete) {
                resolve();
            } else {
                img.onload = resolve;
                img.onerror = resolve; // 即使图片加载失败也继续
            }
        });
    });

    return Promise.all(imagePromises);
};

/**
 * 将Tiptap HTML内容转换为PDF文档
 * @param {string} htmlContent - Tiptap HTML内容
 * @param {string} fileName - 文件名
 * @param {Object} options - 导出选项
 */
export const convertTiptapToPdf = async (htmlContent, fileName = '文档', options = {}) => {
    try {
        if (!htmlContent) throw new Error('文档内容为空');

        // 1. 统一宽度为A4像素宽度
        const a4WidthPx = 794; // 210mm * 3.78
        const a4HeightPx = 1123; // 297mm * 3.78

        const container = document.createElement('div');
        container.style.position = 'absolute';
        container.style.left = '-9999px';
        container.style.top = '0';
        container.style.width = `${a4WidthPx}px`;
        container.style.padding = '40px';
        container.style.fontFamily = 'Arial, sans-serif';
        container.style.fontSize = '14px';
        container.style.lineHeight = '1.6';
        container.style.backgroundColor = 'white';
        container.style.color = 'black';
        container.style.border = '1px solid #ddd';
        container.innerHTML = htmlContent;

        // 补充 blockquote 样式
        const styleTag = document.createElement('style');
        styleTag.innerHTML = `
        blockquote {
            border-left: 4px solid #ccc;
            margin: 16px 0;
            padding-left: 16px;
            color: #666;
            background: #f8f8f8;
            font-style: italic;
        }
        `;
        container.prepend(styleTag);

        // 补充代码块样式
        const codeStyleTag = document.createElement('style');
        codeStyleTag.innerHTML = `
        pre {
            background-color: #f5f5f5;
            padding: 12px;
            border-radius: 4px;
            font-family: 'Courier New', monospace;
            margin: 8px 0;
            overflow-x: auto;
            border: 1px solid #e0e0e0;
        }
        code {
            background-color: #f5f5f5;
            padding: 2px 4px;
            border-radius: 2px;
            font-family: 'Courier New', monospace;
            font-size: 0.9em;
        }
        `;
        container.prepend(codeStyleTag);

        // 关键：限制图片最大宽度
        const imgs = container.querySelectorAll('img');
        imgs.forEach(img => {
            img.style.maxWidth = '100%';
            img.style.height = 'auto';
            img.style.display = 'block';
        });

        document.body.appendChild(container);

        try {
            await waitForImages(container);

            // 2. 用统一的宽度生成canvas
            const canvas = await html2canvas(container, {
                scale: 2,
                useCORS: true,
                allowTaint: true,
                backgroundColor: '#ffffff',
                width: a4WidthPx,
                height: container.scrollHeight,
                scrollX: 0,
                scrollY: 0,
                windowWidth: a4WidthPx,
                windowHeight: container.scrollHeight,
                logging: false,
                ...options.html2canvas
            });

            // 3. 计算图片在PDF中的高度
            const pdf = new jsPDF({
                orientation: 'portrait',
                unit: 'mm',
                format: 'a4',
                ...options.jsPDF
            });

            const imgWidth = 210; // A4宽度mm
            const pageHeight = 297; // A4高度mm
            const imgHeight = (canvas.height * imgWidth) / canvas.width;
            let heightLeft = imgHeight;
            let position = 0;

            // 4. 分页插入图片
            const imgData = canvas.toDataURL('image/png');
            pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
            heightLeft -= pageHeight;

            while (heightLeft > 0) {
                position = heightLeft - imgHeight;
                pdf.addPage();
                pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
                heightLeft -= pageHeight;
            }

            pdf.save(`${fileName}.pdf`);
        } finally {
            document.body.removeChild(container);
        }
    } catch (error) {
        throw new Error(`PDF导出失败: ${error.message}`);
    }
};

/**
 * 批量导出多个文档为PDF
 * @param {Array} docs - 文档数组，每个文档包含 html 和 name 属性
 * @param {Object} options - 导出选项
 * @returns {Promise<number>} 成功导出的文档数量
 */
export const batchExportToPdf = async (docs, options = {}) => {
    let successCount = 0;

    for (const doc of docs) {
        try {
            await convertTiptapToPdf(doc.html, doc.name, options);
            successCount++;
            // 添加延迟避免浏览器阻止多个下载
            await new Promise(resolve => setTimeout(resolve, 1000));
        } catch (error) {
            console.error(`导出PDF文档 "${doc.name}" 失败:`, error);
        }
    }

    return successCount;
};